/**
 * 
 */
package com.zufangbao.earth.web.interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;

import com.zufangbao.earth.web.controller.SettingControllerSpec;
import com.zufangbao.gluon.spec.earth.GlobalSpec4Earth;

/**
 * @author wukai
 *
 */
public class ViewCategoryValidationInterceptor extends
		HandlerInterceptorAdapter {
	
	private static final Log logger = LogFactory.getLog(ViewCategoryValidationInterceptor.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws Exception{
		
		logger.info("interception of request with ViewCategoryValidationInterceptor,context path "+request.getContextPath()+",request url" + request.getRequestURI()+ "," + request.getServletPath());
		
		if(!(handler instanceof HandlerMethod)){
			
			return super.preHandle(request, response, handler);
		}
		
		HandlerMethod handlerMethod = (HandlerMethod)handler;
		
		ViewCategoryValidation viewCategoryValidation = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), ViewCategoryValidation.class);
		
		if(null == viewCategoryValidation){
			
			return super.preHandle(request, response, handler);
		}
		
		Cookie cookie = WebUtils.getCookie(request, GlobalSpec4Earth.PARAM_VIEW_CATEGORY);
		
		if(cookie == null){
			
			logger.info("cookie is null,redirect to list app page");
			
			String targetUrl = request.getServletPath();
			
			if(StringUtils.isNotEmpty(viewCategoryValidation.targetUrl())){
				
				logger.info("redirect to target url["+viewCategoryValidation.targetUrl()+"]");
				
				targetUrl = viewCategoryValidation.targetUrl();
			}
			
			response.sendRedirect(request.getContextPath() + SettingControllerSpec.NAME + SettingControllerSpec.IAppBriefList.NAME + "?targetUrl=" + targetUrl);
			
			return false;
		}
		return super.preHandle(request, response, handler);
	}

}
